package com.leet.code.thread;

public class Code1115 {
    public static void main(String[] args) {
        FooBar fooBar = new FooBar(5);

        Thread f = new Thread(() -> {
            try {
                fooBar.foo(() -> {
                    System.out.print("Foo");
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread b = new Thread(() -> {
            try {
                fooBar.bar(()->{
                    System.out.println("Bar");
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        b.start();
        f.start();


    }

    static class FooBar {

        boolean b = false;

        private int n;

        public FooBar(int n) {
            this.n = n;
        }

        public synchronized void foo(Runnable printFoo) throws InterruptedException {
            b = true;
            for (int i = 0; i < n; i++) {
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                this.notify();
                if (i < n - 1) {
                    this.wait();
                }
            }
        }

        public synchronized void bar(Runnable printBar) throws InterruptedException {

            if (!b) {
                this.wait();
            }
            for (int i = 0; i < n; i++) {
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                this.notify();
                if (i < n - 1) {
                    this.wait();
                }
            }
        }
    }


}
